<template>
  <div class="edit-popup">
    <popup ref="popupRef" :title="popupTitle" :async="true" width="700px" @confirm="handleSubmit" @close="handleClose">
      <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">

        <el-form-item label="院区/楼栋" prop="cb_ids">
          <el-cascader class="flex-1" :options="optionsData.building" clearable v-model="formData.cb_ids"
                       :onchange="set_form_date('cb')" filterable/>
        </el-form-item>

        <el-form-item label="房间名" prop="name">
          <el-input v-model="formData.name" clearable placeholder="请输入房间名"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址"/>
        </el-form-item>
        <!--                <el-form-item label="状态" prop="status">-->
        <!--                    <el-radio-group v-model="formData.status" placeholder="请选择状态">-->
        <!--                        <el-radio v-for="(item, index) in dictData.show_status" :key="index" :label="parseInt(item.value)">-->
        <!--                            {{ item.name }}-->
        <!--                        </el-radio>-->
        <!--                    </el-radio-group>-->
        <!--                </el-form-item>-->

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type" placeholder="请选择类型">
            <el-radio v-for="(item, index) in pagerExtend.type_list" :key="index" :label="parseInt(index)">
              {{ item }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="科室" prop="room_department">
          <el-input v-model="formData.room_department" placeholder="请输入科室"/>
        </el-form-item>

        <el-form-item label="电梯费类型" prop="lift_type">
          <el-radio-group v-model="formData.lift_type" placeholder="请选择电梯费类型">
            <el-radio v-for="(item, index) in pagerExtend.lift_list" :key="index" :label="parseInt(index)">
              {{ item }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" style="width: 200px;" :min="1"/>
        </el-form-item>

        <el-form-item label="住户管理" prop="user">
          <template #default>
            <el-row style="width: 100%;" v-for="(user_value, user_index) in formData.user" :key="user_index">
              <!--              <el-col :span="2">-->
              <!--                <div>{{ user_index + 1 }}：</div>-->
              <!--              </el-col>-->
              <el-col :span="10">
                <el-input v-model="user_value.user_name" placeholder="请输入住户姓名" style="margin-bottom: 10px;"/>
              </el-col>
              <el-col :span="1"></el-col>
              <el-col :span="10">
                <el-input v-model="user_value.user_mobile" placeholder="请输入住户联系方式"
                          style="margin-bottom: 10px;"/>
              </el-col>
              <el-col :span="1"></el-col>
              <!--              <el-col :span="2">-->
              <!--                <el-button v-if="user_index===0" type="primary" @click="userAdd()">新增</el-button>-->
              <!--                <el-button v-else type="warning" @click="userDelete(user_index)">删除</el-button>-->
              <!--              </el-col>-->
            </el-row>
          </template>
        </el-form-item>

        <!--                <el-form-item label="上月总电费" prop="device_total">-->
        <!--                    <el-input v-model="formData.device_total" clearable placeholder="请输入上月总电费" />-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="收费时间" prop="device_fee_time">-->
        <!--                  <el-date-picker-->
        <!--                      class="flex-1 !flex"-->
        <!--                      v-model="formData.device_fee_time"-->
        <!--                      clearable-->
        <!--                      type="datetime"-->
        <!--                      value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--                      placeholder="选择收费时间">-->
        <!--                  </el-date-picker>-->
        <!--                </el-form-item>-->
        <!--                <el-form-item label="排序" prop="sort">-->
        <!--                    <el-input v-model="formData.sort" clearable placeholder="请输入排序" />-->
        <!--                </el-form-item>-->

      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="roomHospitalEdit">

import type {FormInstance} from 'element-plus'
import Popup from '@/components/popup/index.vue'
import {apiRoomHospitalAdd, apiRoomHospitalEdit, apiRoomHospitalDetail} from '@/api/room/room_hospital'
import {apiFindUser} from '@/api/user'
import {timeFormat} from '@/utils/util'
import type {PropType} from 'vue'
import {useDictOptions} from "@/hooks/useDictOptions";
import {selectBuilding, selectDevice, selectRoomHospital} from "@/api/campus";

defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  },
  pagerExtend: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  },
})

const user_set = reactive({
  list: [],
  loading: false
})

const {optionsData} = useDictOptions<{
  building: any[],
}>({
  building: {
    api: selectBuilding
  },
})

const set_form_date = async (data_key: string) => {
  if (data_key == 'cb') {
    if (formData.cb_ids.length == 2) {
      formData.cid = formData.cb_ids[0]
      formData.bid = formData.cb_ids[1]
    } else {
      formData.cid = ''
      formData.bid = ''
    }
  }
}

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
// 弹窗标题
const popupTitle = computed(() => {
  if (mode.value == 'edit') {
    return '编辑全院房间管理';
  } else {
    userAdd();
    return '新增全院房间管理';
  }
})

// 表单数据
const formData = reactive({
  id: '',
  cid: '',
  bid: '',
  cb_ids: '',
  name: '',
  address: '',
  status: 1,
  type: 0,
  lift_type: 100,
  sort: 10000,
  user_id: null,
  device_total: '',
  device_fee_time: null,
  lift_fee: '',
  second_pressure_fee: '',
  user: [],
  room_department: '',
})

// 表单验证
const formRules = reactive<any>({
  cb_ids: [{
    required: true,
    message: '请选择院区/楼栋',
    trigger: ['blur']
  }],
  cid: [{
    required: true,
    message: '请选择院区',
    trigger: ['blur']
  }],
  bid: [{
    required: true,
    message: '请选择楼栋',
    trigger: ['blur']
  }],
  name: [{
    required: true,
    message: '请输入房间名',
    trigger: ['blur']
  }],
  status: [{
    required: true,
    message: '请选择状态',
    trigger: ['blur']
  }],
  type: [{
    required: true,
    message: '请选择类型',
    trigger: ['blur']
  }],
  lift_type: [{
    required: true,
    message: '请选择电梯费类型',
    trigger: ['blur']
  }],
})

// 查询用户
const find_user = async (data: Record<any, any>) => {
  const user_list = await apiFindUser({
    cid: formData.cid,
    keyword: data
  });
  user_set['list'] = user_list
}

const first_user = async (data: Record<any, any>) => {
  const user_list = await apiFindUser({
    cid: data.cid,
    user_id: data.user_id,
    keyword: '',
  });
  user_set['list'] = user_list
}

// 获取详情
const setFormData = async (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
  first_user(data)
}

const getDetail = async (row: Record<string, any>) => {
  const data = await apiRoomHospitalDetail({
    id: row.id
  })
  setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
  await formRef.value?.validate()
  const data = {...formData,}
  mode.value == 'edit'
      ? await apiRoomHospitalEdit(data)
      : await apiRoomHospitalAdd(data)
  popupRef.value?.close()
  emit('success')
}

//打开弹窗
const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
  emit('close')
}

const userAdd = () => {
  formData.user.push({
    user_id: '',
    user_name: '',
    user_mobile: '',
  });
}
const userDelete = (index: number) => {
  formData.user.splice(index, 1);
}

defineExpose({
  open,
  setFormData,
  getDetail
})


</script>
